package com.briup.gsauestore.service.impl;

import com.briup.gsauestore.bean.User;
import com.briup.gsauestore.dao.IUserDao;
import com.briup.gsauestore.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Objects;

/**
 * @author adam
 * @date 2022/1/13
 */
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private IUserDao userDao;

    @Override
    public User login(String name, String password) throws Exception {
        User user = userDao.findByLoginName(name);
        //  判断用户是否存在
        if (Objects.isNull(user)) {
            throw new Exception("用户不存在");
        } else {
            //  判断账号状态
            if (user.isLock()) {
                throw new Exception("账号锁定请联系管理员");
            } else {
                // 校验密码是否相等
                if (user.getPasswordMd5().equals(DigestUtils.md5DigestAsHex(password.getBytes()))) {
                    //    通过验证返回用户信息
                    return user;
                } else {
                    throw new Exception("用户名密码错误");
                }
            }
        }

    }

    @Override
    public void register(User user) throws Exception {
        User user1 = userDao.findByLoginName(user.getLoginName());
//        判断用户名是否存在
        if (Objects.isNull(user1)) {
            userDao.save(user);
        }else{
            throw new Exception("用户名被占用 请更换重试");
        }

    }
}
